package com.huarui.permission.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.huarui.permission.dataobject.Action;
import com.huarui.permission.service.ActionService;


/**
 * 缓存{actionName,methodName}->到PermissionId的映射关系
 * @author uniseraph
 *
 */
public class ActionServiceImpl implements ActionService {

/*	public static class ActionKey {
		private String actionName;
		private String methodName;
		public String getActionName() {
			return actionName;
		}
		public void setActionName(String actionName) {
			this.actionName = actionName;
		}
		public String getMethodName() {
			return methodName;
		}
		public void setMethodName(String methodName) {
			this.methodName = methodName;
		}
		
		
	}*/
	
	private JdbcTemplate  jdbcTemplate;
	
	 Map< String   , Integer>  url2permissionId = new HashMap<String, Integer>()
	;
	
	@SuppressWarnings("unchecked")
	public void init(){
		
		int index =0 ;
		int offset = 100 ;
		
		do {
			
			/**
			 * TODO: 待优化
			 */
			
			List<Action>  actions = jdbcTemplate.query(
					"select id , actionName , methodName , permissionId from action order by id asc limit ? , ? ",
						new Object[]{ index , offset}, new RowMapper(){

							@Override
							public Object mapRow(ResultSet rs, int rowNum)
									throws SQLException {
								Action action =new Action();
								action.setId(rs.getInt(1));
								action.setActionName(rs.getString(2));
								action.setMethodName(rs.getString(3));
								action.setPermissionId(rs.getInt(4));
								return action;
							}});
			
			if(actions==null || actions.isEmpty()){
				return ;
			}
			
			for (Action action : actions) {
					url2permissionId.put(String.format("%s@%s", action.getActionName(),action.getMethodName()), action.getPermissionId());
				
			}
			
			index += offset;
			
		}while(true);
		
		
	}
	
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}


	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}


	@Override
	public Integer getPermissionId(String actionName, String methodName) {
		
		
	
		return url2permissionId.get(String.format("%s@%s", actionName,methodName));
	}

}
